// pages/cart/cart.js
const interfaces = require("../../utils/request.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // datetimeTo: "2019-11-20 12:00:00",
    // timeLeft: ""
    cartGoods: [],
    cartLen: 0,
    count: 0,
    price: 0,
    all: false,
    startX: 0,
    startY: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCart();
    // this.setData({
    //   timeLeft: this.getTimeLeft(this.data.datetimeTo)//使用了util.getTimeLeft
    // });
    // let timer = setInterval(()=>{
    //   this.setData({
    //     timeLeft: this.getTimeLeft(this.data.datetimeTo)//使用了util.getTimeLeft
    //   });
    //   if (this.data.timeLeft == "0天0时0分0秒") {
    //     clearInterval(this.data.timer);
    //   }
    // },1000)
  },
  /**
   * 获取不同商品的总数量
   */
  getCart() {
    let openId = wx.getStorageSync('openId');
    let self = this;
    if (openId) {
      wx.request({
        url: interfaces.cartList,
        data: {
          openId: openId
        },
        success(res) {
          console.log(res)
          let cardList = res.data.data;
          cardList.forEach((item)=>{
            item.checked = false;
            item.isTouchMove = false;
          })
          //console.log(cardList)
          self.setData({
            cartGoods: cardList,
            cartLen: cardList.length,
            price: 0
          })
        }
      })
    } else {
      //console.log(this.data.cartGoods)
      return
    }
  },
  /**
   * 选择商品
   */
  changeColor(e){
    //console.log(e)
    let index = e.currentTarget.dataset.index;
    let cartGoods = this.data.cartGoods;
    let price = this.data.price;
    let selectAll = this.data.all;
    cartGoods[index].checked = !cartGoods[index].checked;
    if (cartGoods[index].checked){
      price += cartGoods[index].number * cartGoods[index].retail_price;
    }else{
      price -= cartGoods[index].number * cartGoods[index].retail_price;
      selectAll = false;
    }
    this.setData({
      cartGoods: cartGoods,
      price: price,
      all: selectAll
    })
  },
  /**
   * 全选
   */
  cartAll(){
    let cartGood = this.data.cartGoods;
    let selectAll = this.data.all;
    let totalMoney = 0;
    selectAll = !selectAll;
    cartGood.forEach(item=>{
      item.checked = selectAll
      if(item.checked){
        totalMoney += item.number * item.retail_price
      }else{
        totalMoney = 0
      }
    })
    this.setData({
      cartGoods: cartGood,
      all: selectAll,
      price: totalMoney
    })
  },
  toDer(){
    let cartGood = this.data.cartGoods;
    let openId = wx.getStorageSync('openId');
    let isCheck = cartGood.some(item=>{
      return item.checked == true
    })
    if(isCheck){
      let newGoods = cartGood.filter(item=>{
        return item.checked == true
      })
      let newGoodsId = [];
      newGoods.forEach(goods=>{
        newGoodsId.push(goods.goods_id)
      })
      let goodsId = newGoodsId.join();
      wx.request({
        url: interfaces.sumitDer,
        method: "POST",
        data:{
          goodsId: goodsId,
          openId: openId,
          allPrise: this.data.price
        },
        success(res){
          //console.log(res)
          wx.navigateTo({
            url: '/pages/order/order'
          })
        }
      })
      //console.log(goodsId)
    }else{
      wx.showToast({
        title: "请选择商品",
        icon: "none"
      });
      wx.navigateTo({
        url: '/pages/order/order'
      })
    }
  },
  del(e){
    let index = e.currentTarget.dataset.index;
    let cartGood = this.data.cartGoods;
    let self = this;
    wx.showModal({
      title: '',
      content: '是否删除该商品',
      success(res){
        if(res.confirm){
          wx.request({
            url: interfaces.del,
            data: {
              id: cartGood[index].id
            },
            success(res) {
              self.getCart();
            }
          })
        }
      }
    })
  },
  /**
   * 手指触摸动作开始 记录起点X坐标
  */
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.cartGoods.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      cartGoods: this.data.cartGoods
    })
  },
  /**
   * 滑动事件处理
  */
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });

    this.data.cartGoods.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX){//右滑
          v.isTouchMove = false
        } else if (startX == touchMoveX){
          
        }
        else{//左滑
          v.isTouchMove = true
        }

      }
    })

    //更新数据
    that.setData({
      cartGoods: that.data.cartGoods
    })
  },
  /**
   * 计算滑动角度
  */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  // //取倒计时（天时分秒）
  // getTimeLeft(datetimeTo){
  //   // 计算目标与现在时间差（毫秒）
  //   let time1 = new Date(datetimeTo).getTime();
  //   let time2 = new Date().getTime();
  //   let mss = time1 - time2;

  //   // 将时间差（毫秒）格式为：天时分秒
  //   let days = parseInt(mss / (1000 * 60 * 60 * 24));
  //   let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  //   let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  //   let seconds = parseInt((mss % (1000 * 60)) / 1000);

  //   return days + "天" + hours + "时" + minutes + "分" + seconds + "秒"
  // },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})